#encoding 'utf-8'

load 'rds_api.rb'
load 'tutem_utils.rb'
@rds = @rds_tt

def export_orders_by cond = ''
    orders = {}
    sql = "select o.*, p.text, p.goods_info, p.pcode_info, p.actual_paid, p.refunded_amount from tutem_mall.eb_store_order o left join tutem_mall.eb_pickup_book p on (o.id = p.oid) where o.paid = 1"
    sql += " #{cond}" if cond != ''
    (queryRds(sql)).each do |q|
        order = {}
        order.store 'id', q['id']
        order.store 'code', q['order_code']
        order.store 'time', Time.at(q['pay_time']).strftime('%Y-%m-%d %H:%M:%S')

        status = '待发货'
        case q['status']
        when 0
            status = '待发货'
        when 1
            status = '待收货'
        when 2
            status = '已收货'
        when 3
            status = '已评价'
        else
            status = '不明确'
        end
        order.store 'status', status

        refund = '无维权'
        case q['refund_status']
        when 0
            refund = '无维权'
        when 1
            refund = '想退款'
        when 2
            refund = '已处理'
        else
            refund = '不明确'
        end
        order.store 'refund', refund

        order.store 'paid', q['actual_paid']
        order.store 'refunded', q['refunded_amount']
        order.store 'att!', q['refunded_amount'] > 0 ? '!' : ''

        order.store 'ship', q['delivery_name'].to_s + q['delivery_id'].to_s

        goods_info = q['goods_info']
        goods = JSON.parse q['goods_info']
        products = {}
        goods.each do |g|
            pcode = g['pcode']
            info = {}
            info.store 'pcode', g['pcode']
            info.store 'paid', g['weixin_paid'] + g['tupay_paid']
            info.store 'qty', g['standard_qty']
            products.store pcode, info
        end
        (typical_goods_codes + ['OTHR']).each do |pcode|
            if products[pcode].nil?
                products.store pcode, {'pcode'=>pcode, 'paid'=>0.00, 'qty'=>0}
            end
            order.store "#{pcode}-qty", products[pcode]['qty']
            order.store "#{pcode}-paid", products[pcode]['paid']
        end

        order.store 'remark', q['remark']

        order.store 'uid', q['uid']
        order.store 'name', q['real_name']
        order.store 'phone', q['user_phone']
        order.store 'addr', q['user_address']

        orders.store q['id'], order
    end
    return orders
end

def export_20221001
    start = Time.parse('2022-10-01 00:00:00').to_i
    cond = " and o.pay_time >= #{start}"
    orders = export_orders_by cond
    dump_hash_to_excel orders, 'orders_since_20221001.xls'
end
